<?php
namespace app\app\controller\v1;
use app\app\model\Address;
use app\app\util\OnlineUtils;

class AddressController extends BaseController{

	/**
	 * [addNewAddress 添加新地址]
	 * @param $user_id string 用户id 
	 * @param $id int id
	 */
	public function addNewAddress()
	{
		$user_id = OnlineUtils::getUserIdBySid();
		$Address = new Address();
		$data    = array(
			'name'    => input('post.name'),
			'phone'   => input('post.phone'),
			'address' => input('post.address'),
			'details' => input('post.details')
		);
		$result = $this->validate($data,'Address');
			if(true !== $result){
			// 验证失败 输出错误信息
			return jsonReturn(402,$result);
		}
		$data['user_id'] = $user_id;
		$data['create_time'] = time();
		//先插入地址表
		$Address->save($data);
		$id = $Address->id;
		return jsonReturn(200,'success',$id);
	}

	/**
	 * [getAllAddress 获取所有的地址]
	 * @param $[user_id] [用户id]
	 * @return [type] []
	 */
	public function getAllAddress()
	{
		$user_id = OnlineUtils::getUserIdBySid();
		$Address = new Address();
		$Address->user_id = $user_id;
		$address = $Address->getAll();
		return jsonReturn(200,'success',$address);
	}

	/**
	 * [AddressDelete 删除地址]
	 * @param string $[user_id] [用户id]
	 * @return [json] [description]
	 */
	public function AddressDelete()
	{
		$user_id = OnlineUtils::getUserIdBySid();
		$address = new Address();
		$address->user_id = $user_id;
		$result = $address->del(input('post.id'));
		return jsonReturn($result['code'],$result['msg']);
	}

	/**
	 * [AddressUpdate 更新地址]
	 * @param [type] $[name] [description]
	 */
	public function AddressUpdate()
	{
		$user_id = OnlineUtils::getUserIdBySid();
		$address = new Address();
		$have = $address->get(input('post.id'));
		if( input('post.id') != $have['id'] ) {
			return jsonReturn(402,'地址不存在');
		}
		$data    = array(
			'name'    => input('post.name'),
			'phone'   => input('post.phone'),
			'address' => input('post.address'),
			'details' => input('post.details')
		);
		$result = $this->validate($data,'Address');
			if(true !== $result){
			// 验证失败 输出错误信息
			return jsonReturn(402,$result);
		}
		$data['user_id'] = $user_id;
		$data['create_time'] = time();
		$data['id'] = input('post.id');
		try {
			$address->isUpdate(true)->save($data);	
		} catch (Exception $e) {
			return jsonReturn(402,'更新失败');
		}
		return jsonReturn(200,'更新成功');
	}

}